package com.asynchfileupload.view;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileUploadResourceLoader
 */
public class FileUploadResourceLoader extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String libraryPath="/resources/"; 
	private static Map<String,String> mimeMap  = new HashMap<String,String>();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadResourceLoader() {
        super();
        
        mimeMap.put("css","text/css");
        mimeMap.put("png","image/png");
        mimeMap.put("js","text/javascript");
        mimeMap.put("gif","image/gif");
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String fileName = request.getParameter("name");
		
		StringBuffer requestURL = request.getRequestURL();
		
		fileName = requestURL.substring(requestURL.lastIndexOf("/") + 1).toString();
		
		String fileExtension = null;
		
		if(fileName.lastIndexOf(".") >= 0)
			fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
	
		if(fileExtension!=null)
			response.setContentType(getMimeType(fileExtension));
		
		 OutputStream out = response.getOutputStream();
		
		try
		  {
			InputStream is = this.getClass().getResourceAsStream(libraryPath + fileName);
	         
			if(is != null)
	         {
	        	
			   byte[] buf = new byte[1024];
			    int count = 0;
			    while ((count = is.read(buf)) >= 0) {
			        out.write(buf, 0, count);
			    }
			    is.close();
			    out.close();
		     }
	         else
	         {
	            System.out.println("Error: Unable to retrieve InputStream");
	            response.sendError(404,"Resource not found");
	         }
	      }
	      catch (Exception e)
	      {
	         System.out.println(e);
	      }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public static String getMimeType(String extension)
	{
		return mimeMap.get(extension);
	}
}
